//
//  LoginViewController.m
//  HaierGMS_APP
//
//  Created by 堂堂 on 16/7/13.
//  Copyright © 2016年 堂堂. All rights reserved.
//

#import "LoginViewController.h"
#import "MainUITabBarController.h"
#import "Prefix.h"
#import "AppDelegate.h"
#import "RegisterViewController.h"
#import "ForgetViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "MBProgressHUD+MJ.h"
#import "HttpReauestParam.h"
#import<CommonCrypto/CommonDigest.h>
#import "Base64Until.h"
#import "UserDefaultUtil.h"
#import <ALBBPush/CloudPushSDK.h>
#import <sys/utsname.h>
@interface LoginViewController ()

@end

@implementation LoginViewController

- (void)viewDidLoad {
    
    
    [super viewDidLoad];
   
    

    
    self.nameField.delegate = self;
    self.pwdField.delegate = self;
   
    //#F6F6F6
    
    UIColor *testColor1= [UIColor colorWithRed:222/255.0 green:120/255.0 blue:0/255.0 alpha:1];
    UIColor *testColor2= [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1];

    self.loginBtn.backgroundColor = testColor1;
    self.registBtn.backgroundColor = testColor2;
    
    [self.loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    
    [self.registBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.registBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    
    self.navigationController.navigationBar.hidden = YES;

    // 设置状态栏
    //[UIApplication sharedApplication].statusBarStyle = UIBarStyleBlackOpaque;
    
    
    
}
- (NSString *) md5:(NSString *) input {
    const char *cStr = [input UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    return  output;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if([textField isFirstResponder]){
        [textField  resignFirstResponder];
    }
    return YES;
}
- (IBAction)pressButton:(UIButton *)sender {
    if([self.nameField isFirstResponder]){
        [self.nameField  resignFirstResponder];
    }
    if([self.pwdField isFirstResponder]){
        [self.pwdField  resignFirstResponder];
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


-(void)viewDidAppear:(BOOL)animated{
    NSLog(@"viewDidAppear");
}
- (void)viewWillAppear:(BOOL)animated{
     NSLog(@"viewWillAppear");
}
-(void)viewWillDisappear:(BOOL)animated{
    NSLog(@"viewWillDisappear");

    //self.navigationController.navigationBar.hidden = YES;
}


- (IBAction)touchView:(id)sender {
    [self.view endEditing:YES];  
}


- (IBAction)loginAction:(id)sender {
    
    
    NSLog(@"%@",self.pwdField.text);
    
    if ([self.nameField.text isEqualToString:@""]) {
        [MBProgressHUD showError:@"请输入手机号"];
        
        return;
    }
    if ([self.pwdField.text isEqualToString:@"" ]) {
        [MBProgressHUD showError:@"请输入密码"];
        
        return;
    }
    [MBProgressHUD showMessage:@"登录中"];
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    NSMutableDictionary *dic  =  [[NSMutableDictionary alloc]init];
    [dic setObject:[Base64Until encode:self.pwdField.text] forKey:@"password"];
    [dic setObject:self.nameField.text forKey:@"phone"];
    [dic setObject:[self deviceVersion] forKey:@"client_type"];
    [dic setObject:appCurVersion forKey:@"app_version"];
    [dic setObject:@"" forKey:@"last_message_time"];
    
    
    HttpReauestParam * param = [[HttpReauestParam alloc]initWithData:@"app_system_loginIos" content:[self dictionaryToJson:dic ] urlType:0];
    
   
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:param.SEVICE_URL parameters:param.param
          success:^(AFHTTPRequestOperation *operation, id responseObject){
              [MBProgressHUD hideHUD];
              
              NSString *result  =[[ NSString alloc] initWithData:operation.responseData encoding:NSUTF8StringEncoding];
              
              NSDictionary *data = [NSJSONSerialization JSONObjectWithData:operation.responseData options:0 error:nil];
            
              
              if ( [[data objectForKey:@"success"] boolValue]) {
                  NSLog(@"登录成功");
                  
                  NSDictionary *userData = data[@"result"];
                  //保存数据
                   [UserDefaultUtil saveData:userData[@"identifier"] key:USER_ID];
                   [UserDefaultUtil saveData:userData[@"login_name"] key:USER_PHONE];
                   [UserDefaultUtil saveData:self.pwdField.text key:USER_PWD];
                   [UserDefaultUtil saveData:userData[@"auth_status"] key:USER_STATUS];
                   [UserDefaultUtil saveData:userData[@"user_name"] key:USER_NAME];
                  [CloudPushSDK addTag:userData[@"identifier"] withCallback:^(BOOL success) {
                      NSLog(@"绑定成功");
                  }];
                  
                  //跳转
                   UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
                               //由storyboardID获取TabBarViewController
                   MainUITabBarController * myTabBarController = [storyboard instantiateViewControllerWithIdentifier:@"main_tabbar"];
                  
                   [self presentViewController:myTabBarController animated:YES completion:nil];

                  
                  
              }else{
                  [MBProgressHUD showError:[data objectForKey:@"errorMsg"]];
              }
              
              NSLog(@"%@",result);
    
    }
     
     failure:^(AFHTTPRequestOperation *operation, NSError *error){
         [MBProgressHUD hideHUD];
         [MBProgressHUD showError:@"登录失败"];
     }];
}
- (IBAction)registerClick:(id)sender {
    
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
    
    
    
    //由storyboardID获取TabBarViewController
    RegisterViewController * registerController = [storyboard instantiateViewControllerWithIdentifier:@"register_view"];
    
    
    [self presentViewController:registerController animated:YES completion:nil];
}

- (IBAction)pwdAction:(id)sender {
}
- (IBAction)forget_Click:(id)sender {
    
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
    
    
    
    //由storyboardID获取TabBarViewController
    ForgetViewController * forgetController = [storyboard instantiateViewControllerWithIdentifier:@"forget_view"];
    
    
    [self presentViewController:forgetController animated:YES completion:nil];

}

-(NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

- (NSString*)deviceVersion
{
    // 需要#import "sys/utsname.h"
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString * deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    //iPhone
    if ([deviceString isEqualToString:@"iPhone1,1"])    return @"iPhone 1G";
    if ([deviceString isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
    if ([deviceString isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
    if ([deviceString isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    if ([deviceString isEqualToString:@"iPhone3,2"])    return @"Verizon iPhone 4";
    if ([deviceString isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([deviceString isEqualToString:@"iPhone5,1"])    return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone5,2"])    return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone5,3"])    return @"iPhone 5C";
    if ([deviceString isEqualToString:@"iPhone5,4"])    return @"iPhone 5C";
    if ([deviceString isEqualToString:@"iPhone6,1"])    return @"iPhone 5S";
    if ([deviceString isEqualToString:@"iPhone6,2"])    return @"iPhone 5S";
    if ([deviceString isEqualToString:@"iPhone7,1"])    return @"iPhone 6 Plus";
    if ([deviceString isEqualToString:@"iPhone7,2"])    return @"iPhone 6";
    if ([deviceString isEqualToString:@"iPhone8,1"])    return @"iPhone 6s";
    if ([deviceString isEqualToString:@"iPhone8,2"])    return @"iPhone 6s Plus";
    
    　return deviceString;
}
@end
